<?php

/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables = '*')
{
	$link = mysql_connect($host,$user,$pass);
	mysql_select_db($name,$link);
	
	//get all of the tables
	if($tables == '*')
	{
		$tables = array();
		$result = mysql_query('SHOW TABLES');
		while($row = mysql_fetch_row($result))
		{
			$tables[] = $row[0];
		}
	}
	else
	{
		$tables = is_array($tables) ? $tables : explode(',',$tables);
	}
	
	//cycle through
	foreach($tables as $table)
	{
		$result = mysql_query('SELECT * FROM '.$table);
		$num_fields = mysql_num_fields($result);
		$return.= 'DROP TABLE '.$table.';';
		$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
		$return.= "\n\n".$row2[1].";\n\n";
		
		for ($i = 0; $i < $num_fields; $i++) 
		{
			while($row = mysql_fetch_row($result))
			{
				$return.= 'INSERT INTO '.$table.' VALUES(';
				for($j=0; $j<$num_fields; $j++) 
				{
					$row[$j] = addslashes($row[$j]);
					$row[$j] = ereg_replace("\n","\\n",$row[$j]);
					if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
					if ($j<($num_fields-1)) { $return.= ','; }
				}
				$return.= ");\n";
			}
		}
		$return.="\n\n\n";
	}
	
	//save file
	$backup = 'backup/brevisbb-backup-'.date("d-M-Y__h-i-s").'.sql';
	$handle = fopen($backup,'w+');
	//$handle = fopen('db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');
	echo '<div align="center">Backup successfully created.<br/><br/><a href="'.$backup.'">Download</a><br><br><a href="?del='.$backup.'">Delete file</a><br><br><a href="backup.php">Back to previous page</a></div>';
	fwrite($handle,$return);
	fclose($handle);
}

include ("header.php");	
if($_SESSION['user_level'] != 1 OR (!$_SESSION['signed_in']))
{
header("location: redirect.php");
}
else
 {
$pageTitle = "Backup";
if (mysql_real_escape_string($_GET['del']== '') AND mysql_real_escape_string($_GET['backup']== '1'))
{
backup_tables($server,$username,$password,$database,'*');
}
if (mysql_real_escape_string($_GET['del']!= '') AND mysql_real_escape_string($_GET['backup']!= '1'))
{
echo "<div align='center'><br/> File successfully deleted!</div><br/><br/>";
if (file_exists(mysql_real_escape_string($_GET['del']))){
unlink(mysql_real_escape_string($_GET['del']));}
}
if ( mysql_real_escape_string($_GET['backup']!= '1'))
{
echo "<div align='center'><a class='menuButtons' href ='?backup=1'>Backup database</a></div><br>";
// open this directory 
$myDirectory = opendir("./backup");

// get each entry
while($entryName = readdir($myDirectory)) {
	$dirArray[] = $entryName;
}

// close directory
closedir($myDirectory);

//	count elements in array
$indexCount	= count($dirArray);
$totfiles = $indexCount-2;
if ($totfiles <=0) {$totfiles=0;}
Print ("$totfiles file(s)<br>\n");

// sort 'em
sort($dirArray);

// print 'em
print("<TABLE border=1 cellpadding=5 cellspacing=0 >\n");
print("<TR><TH > &nbsp;<b>Backup files:<b/></TH></TR>\n");
// loop through the array of files and print them all
for($index=0; $index < $indexCount; $index++) {
        if (substr("$dirArray[$index]", 0, 1) != "."){ // don't list hidden files
		print("<TR><TD height='32'>&nbsp;<a href=\"backup/$dirArray[$index]\">$dirArray[$index]</a> | <a href=\"?del=backup/$dirArray[$index]\"><img src='style/$default_style/delete.gif' border='0' align='absmiddle'/>Delete</a></td>");

		print("</TR>\n");
	}
}
print("</TABLE>\n");
}

$pageContents = ob_get_contents ();
ob_end_clean (); 
echo str_replace ('<!--TITLE-->', $pageTitle, $pageContents);  
}
?>